import { sendMobileCode } from '@/apis/user'
import type { CodeType } from '@/types/user'
import { showToast, type FormInstance } from 'vant'
import { onUnmounted, ref, type Ref } from 'vue'

export function useMobileCode(mobile: Ref<string>, type: CodeType = 'login') {
  const formRef = ref<FormInstance>()
  // 发送短信验证码
  const time = ref(0)
  let timerId: number
  const onSend = async () => {
    // 处理是否已经在发送短信验证码
    if (time.value > 0) return
    // 校验是否输入了手机号码 借助于 Vant里面的
    await formRef.value?.validate('mobile')
    // 发送短信验证码
    const res = await sendMobileCode(mobile.value, type)
    // console.log(res.data.code)
    // 显示验证码
    showToast({
      message: res.data.code,
      duration: 5000
    })
    // 处理倒计时
    time.value = 60
    if (timerId) clearInterval(timerId)
    // 开启定时器函数
    timerId = setInterval(() => {
      time.value--
      if (time.value <= 0) {
        clearInterval(timerId)
      }
    }, 1000)
  }

  onUnmounted(() => {
    // 清除定时器
    clearInterval(timerId)
  })

  return {
    onSend,
    time,
    formRef
  }
}